<?php
class Rate extends AppModel {
    public $name         = 'Rate';
    public $displayField = 'code';
    public $validate     = array(
        'room_type_id' => array(
            'rule'    => 'notEmpty',
            'message' => 'Please select a Rate Code'
        ),
        'rate_code_id' => array(
            'rule'    => 'notEmpty',
            'message' => 'Please select a Rate Type'
        ),
        'from' => array(
            'rule'    => 'date',
            'message' => 'Invalid date, must be in DD-MM-YYYY format'
        ),
        'to' => array(
            'rule'    => 'date',
            'message' => 'Invalid date, must be in DD-MM-YYYY format'
        ),
        'description' => array(
            'rule'    => array('between', 5, 255),
            'message' => 'Description must be between 5 and 15 characters long'
        ),
        'd_1' => array(
            'rule'       => array('money', 'left'),
            'allowEmpty' => true,
            'message'    => 'Invalid monetary amount'
        ),
        'd_2' => array(
            'rule'       => array('money', 'left'),
            'allowEmpty' => true,
            'message'    => 'Invalid monetary amount'
        ),
        'd_3' => array(
            'rule'       => array('money', 'left'),
            'allowEmpty' => true,
            'message'    => 'Invalid monetary amount'
        ),
        'd_4' => array(
            'rule'       => array('money', 'left'),
            'allowEmpty' => true,
            'message'    => 'Invalid monetary amount'
        ),
        'e_1' => array(
            'rule'       => array('money', 'left'),
            'allowEmpty' => true,
            'message'    => 'Invalid monetary amount'
        ),
        'e_2' => array(
            'rule'       => array('money', 'left'),
            'allowEmpty' => true,
            'message'    => 'Invalid monetary amount'
        ),
        'e_3' => array(
            'rule'       => array('money', 'left'),
            'allowEmpty' => true,
            'message'    => 'Invalid monetary amount'
        ),
        'e_4' => array(
            'rule'       => array('money', 'left'),
            'allowEmpty' => true,
            'message'    => 'Invalid monetary amount'
        ),
        'extra_adult_weekday' => array(
            'rule'       => array('money', 'left'),
            'allowEmpty' => true,
            'message'    => 'Invalid monetary amount'
        ),
        'extra_adult_weekend' => array(
            'rule'       => array('money', 'left'),
            'allowEmpty' => true,
            'message'    => 'Invalid monetary amount'
        ),
        'extra_child_weekday' => array(
            'rule'       => array('money', 'left'),
            'allowEmpty' => true,
            'message'    => 'Invalid monetary amount'
        ),
        'extra_child_weekend' => array(
            'rule'       => array('money', 'left'),
            'allowEmpty' => true,
            'message'    => 'Invalid monetary amount'
        )
    );
    public $belongsTo = array(
        'Hotel' => array(
            'className' => 'Hotel',
            'fields'    => array('name')
        ),
        'RoomType' => array(
            'className' => 'RoomType',
            'fields'    => array('code', 'description')
        ),
        'RateCode' => array(
            'className' => 'RateCode',
            'fields'    => array('code', 'description')
        )
    );
    public $hasMany = array(
        'RateExceptions' => array(
            'className' => 'RateExceptions',
            'dependent' => true
        )
    );

    public function rateList ($params) {
        $page = $params['page'];
        $cond = 'r.`created` IS NOT NULL ';

        if ($params['query'] && $params['qtype']) {
            $cond .= 'AND r.`'.$params['qtype'].'` LIKE "%'.$params['query'].'%" ';
        }

        $sql = 'SELECT COUNT(*) AS total FROM `rates` AS r ' .
               'WHERE '.$cond;
        $ttl = $this->query($sql);

        $total = (count($ttl) == 0) ? 0 : $ttl[0][0]['total'];
        if ($total == 0) {
            return array(
                'page'  => 1,
                'total' => 0,
                'rows'  => array()
            );
        }

        $rpp   = isset($params['rp']) ? $params['rp'] : 10;
        $start = (($page-1) * $rpp);
        $sort  = empty($params['sortname']) ? 'id' : $params['sortname'];
        $ord   = (empty($params['sortorder']) || $params['sortorder'] == 'asc') ? 'ASC' : 'DESC';
        $sql   = 'SELECT r.*, t.`code`, c.`code` FROM `rates` AS r ' .
                 'INNER JOIN `room_types` AS t ' .
                 'ON r.`room_type_id`=t.`id` ' .
                 'INNER JOIN `rate_codes` AS c ' .
                 'ON r.`rate_code_id`=c.`id` ' .
                 'WHERE '.$cond .
                 'ORDER BY r.`'.$sort.'` '.$ord.' ' .
                 'LIMIT '.$start.', '.$rpp;
        $data = $this->query($sql);
        $rec  = array();

        if (count($data) == 0) {
            return array(
                'page'  => 1,
                'total' => 0,
                'rows'  => array()
            );
        }

        foreach ($data as $rs) {
            $id = $rs['r']['id'];

            $fromDate = ($rs['r']['from']) ? $this->serverToClientTime($rs['r']['from'], 'd-m-Y') : '-';
            $toDate   = ($rs['r']['to']) ? $this->serverToClientTime($rs['r']['to'], 'd-m-Y') : '-';
            $created  = $this->serverToClientTime($rs['r']['created'], 'd/m/Y H:i a');
            $modified = $this->serverToClientTime($rs['r']['modified'], 'd/m/Y H:i a');
            $actions  = '<div class="selectRecord" onclick="rateInfo.select('.$id.');"></div>' .
                        '<div class="editRecord" onclick="rateInfo.edit('.$id.');"></div>';

            $cell = array(
                $id, $rs['r']['room_type_id'], $rs['r']['rate_code_id'], $rs['t']['code'], $rs['c']['code'], $fromDate, $toDate, $rs['r']['description'], $rs['r']['d_1'],
                $rs['r']['e_1'], $rs['r']['d_2'], $rs['r']['e_2'], $rs['r']['d_3'], $rs['r']['e_3'], $rs['r']['d_4'], $rs['r']['e_4'], $rs['r']['extra_adult_weekday'],
                $rs['r']['extra_adult_weekend'], $rs['r']['extra_child_weekday'], $rs['r']['extra_child_weekend'], $created, $modified, $actions
            );

            $rec[] = array(
                'id'   => $id,
                'cell' => $cell
            );
        }

        return array(
            'page'  => $page,
            'total' => $total,
            'rows'  => $rec
        );
    } // rateList

    public function rateDetails ($hotelId, $roomTypeId, $checkin, $checkout, $adult, $child) {
        $inTime  = strtotime($checkin); // check-in time
        $outTime = strtotime($checkout); // check-out time

        $loop = true;
        $pday = 0;
        $amnt = 0;
        $data = array();

        while ($loop == true) {
            $ptime = ($pday * 86400) + $inTime;

            if ($ptime >= $outTime) {
                $loop = false;
                break;
            }

            $date = date('Y-m-d', $ptime);
            $day  = date('l', $ptime);

            $rate = $this->find('first', array(
                'conditions' => array(
                    'Rate.hotel_id'     => $hotelId,
                    'Rate.room_type_id' => $roomTypeId,
                    'Rate.from <='      => $date,
                    'Rate.to >='        => $date
                ),
                'recursive' => -1,
                'fields'    => array('Rate.id', 'Rate.d_1', 'Rate.d_2', 'Rate.d_3', 'Rate.d_4', 'Rate.e_1', 'Rate.e_2', 'Rate.e_3', 'Rate.e_4'),
                'order'     => array('Rate.id DESC')
            ));

            if (!$rate) { // validation of no rate

            }

            if ($day == 'Friday' || $day == 'Saturday') { // weekend rate
                if ($adult >= 1 && $adult <= 4) {
                    $r = $rate['Rate']['e_'.$adult];
                }
            } else {
                if ($adult >= 1 && $adult <= 4) {
                    $r = $rate['Rate']['d_'.$adult];
                }
            }

            $data['rate'][] = array(
                'rate_id' => $rate['Rate']['id'],
                'date'    => $date,
                'day'     => $day,
                'rate'    => $r
            );

            $amnt += $r;
            $pday++;
        }

        $tax  = $amnt * 0.02; // 2% tax from the amount
        $ttl  = number_format($amnt + $tax, 2);
        $tax  = number_format($tax, 2);
        $amnt = number_format($amnt, 2);

        $data['subtotal'] = array(
            'amount'   => $amnt,
            'tax'      => $tax,
            'discount' => '0.00',
            'total'    => $ttl
        );

        return $data;
    } // rateDetails
} // Rate
?>